package com.kgc.cgconsumer.Controller;

import com.kgc.basic.util.ResponseMsg;
import com.kgc.cgconsumer.service.CGConServ;
import com.kgc.cgconsumer.service.CGXJConsumerService;
import com.kgc.cgconsumer.service.CgWorkFlowService;
import com.kgc.cgconsumer.service.ImportExportFeign;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("CGXJ")
public class CGXJController {
    Logger logger = LoggerFactory.getLogger(CGXJController.class);

    private static final String TABLE = "cg_bcgxj";

   @Resource
    private CGXJConsumerService cgxjServ;

   @Resource
   private CGConServ cgConServ;

   @Resource
   private CgWorkFlowService cgWorkFlowService;

    @Resource
    private ImportExportFeign importExportFeign;

    @RequestMapping("getCGXJ")
    public ResponseMsg getCGXJ(String code){
        ResponseMsg responseMsg = cgxjServ.getCGXJ(code);
        return responseMsg;
    }


    @RequestMapping("getPage")
    public ResponseMsg getCGXJPage(@RequestBody Map<String,Object> map){
        ResponseMsg responseMsg = cgxjServ.getCGXJPage(map);
        return responseMsg;
    }

    @RequestMapping("addCGXJ")
    public ResponseMsg addCGXJ(@RequestBody Map<String,Object> map){
        ResponseMsg responseMsg = cgxjServ.addCGXJ(map);

        Map<String,Object> variables = new HashMap<>();
        variables.put("code",responseMsg.getData());//单据编号
        variables.put("type",map.get("type"));//流程类型
        //创建一个流程实例
        com.kgc.activiti.util.ResponseMsg res = cgWorkFlowService.startProcess(variables);
        if (!"200".equals(res.getCode())){
            responseMsg.setCode(res.getCode());
        }
        return responseMsg;
    }

    @RequestMapping("delCGXJ")
    public ResponseMsg delCGXJ(@RequestParam String code){
        ResponseMsg responseMsg = cgConServ.del(TABLE,code);
        return responseMsg;
    }
    @RequestMapping("modiCGXJ")
    public ResponseMsg modiCGXJ(@RequestBody Map<String,Object> map){
        ResponseMsg responseMsg = cgxjServ.modiCGXJ(map);
        return responseMsg;
    }
    @RequestMapping("/check")
    public  ResponseMsg check(@RequestBody Map<String,Object> map){
        ResponseMsg responseMsg = new ResponseMsg();
        logger.info("CGXJController check params,{}",map.toString());
        Map<String,Object> variables = new HashMap<>();
        variables.put("code",map.get("code"));//单据编号
        variables.put("checkManId",Integer.valueOf((String) map.get("checkManId")));//审批人
        variables.put("checkManName",(String) map.get("checkManName"));//审批人
        variables.put("checkComment",(String) map.get("checkComment"));//审批意见
        variables.put("checkDate",new Date());//审批时间
        variables.put("checkRes",(boolean)map.get("checkRes"));//审批结果
        com.kgc.activiti.util.ResponseMsg msg=  cgWorkFlowService.competeTask(variables);
        responseMsg.setCode(msg.getCode());
        responseMsg.setMsg(msg.getMsg());
        return responseMsg;
    }


    //下载模板
    @RequestMapping(value = "/template", method = RequestMethod.GET)
    public void downTemplate(HttpServletResponse response) {
        logger.info("consumer CustomerController downTemplate is start...");
        try {
            ResponseMsg responseMsg = importExportFeign.downLoadTemplate("com.kgc.cgapi.pojo.CGXJPojo");
            if ("200".equals(responseMsg.getCode())) {
                String base64Data = (String) responseMsg.getData();
                byte[] templateData = Base64.getDecoder().decode(base64Data);   //解码

                //设置响应头
                response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                response.setCharacterEncoding("UTF-8");
                String filename = URLEncoder.encode("采购询价导入信息表.xlsx", "UTF-8");
                response.setHeader("Content-Disposition", "attachment; filename=" + filename);

                response.getOutputStream().write(templateData);
            } else {
                logger.error("下载模板失败, status: {}", responseMsg.getMsg());
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            }
        } catch (IOException e) {
            logger.error("consumer CustomerController downTemplate is error", e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }

    //导入
    @RequestMapping(value = "/import", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseMsg importInfo(@RequestPart("file") MultipartFile file) {
        logger.info("consumer CustomerController importInfo fileName:{}", file.getOriginalFilename());
        return importExportFeign.importInfo(file, "com.kgc.cgapi.pojo.CGXJPojo", "code", "");
    }

    @RequestMapping(value = "/export")
    public void exportCGXJ(@RequestBody Map<String, Object> map, HttpServletResponse response) {
        logger.info("consumer exportCGXJ exportSalesInvoices params:{}", map);
        try {
            ResponseMsg responseMsg = importExportFeign.exportEntities(map, "com.kgc.cgapi.pojo.CGXJPojo", "create_date desc");
            if ("200".equals(responseMsg.getCode())) {
                String base64Data = (String) responseMsg.getData();
                byte[] exportData = Base64.getDecoder().decode(base64Data);

                //设置响应头
                response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                response.setCharacterEncoding("UTF-8");
                String filename = URLEncoder.encode("采购询价信息表.xlsx", "UTF-8");
                response.setHeader("Content-Disposition", "attachment; filename=" + filename);

                response.getOutputStream().write(exportData);
            } else {
                logger.error("导出失败, msg: {}", responseMsg.getMsg());
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            }
        } catch (IOException e) {
            logger.error("consumer SalesInvoiceController exportSalesInvoices is error", e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }

}
